package cn.good.yan.basics.t3.service;

import cn.good.yan.basics.t3.mapper.ProviderMapper;
import cn.good.yan.basics.t3.pojo.Provider;
import cn.good.yan.basics.t3.utils.RedisC;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * Redis 操作案例
 *      注解版
 * @author shengren.yan
 * @create 2022-11-24
 */
@CacheConfig(cacheNames="provider")
@Service
public class ProviderService2 {

    // Redis工具类
    @Autowired(required = false)
    private RedisC redisClient;

    @Autowired(required = false)
    ProviderMapper providerMapper;

    /**
     * cacheNames 缓存名字
     * key:缓存容器中的key值, 方法返回值是value值
     * @param id
     * @return
     */
    //必须 指定一个缓存名称，不指定报500
    @Cacheable(/*cacheNames = "provider",*/ key = "#id")
    public Provider addById(Integer id){
        Provider provider = new Provider();
        provider.setPid(5);
        provider.setProviderCode("注解版-北京");
        provider.setFax("ssss1");
        // 新增
        System.out.println("操作 -添加数据库"+ id);
        return provider;
    }

    // 修改
    //必须 指定一个缓存名称，不指定报500
    @CachePut(/*cacheNames = "provider",*/ key="#result.id")
    public Provider updateUser(Provider provider){
        // 更新数据库
        System.out.println("操作 -更新数据库" + provider);
        return provider;
    }

    // 删除
    @CacheEvict(/*cacheNames = "provider",*/ key="#id", allEntries = true/*, beforeInvocation = true*/)
    public Integer deleteUserById(Integer id){
//        int i = 1/0;
        // 删除数据库
        return id;
    }


    public Provider getByPid(Integer pid){
        // 1.先查询一下缓存中是否有数据
        Object obj = redisClient.get("provider" + pid);
        if(obj != null) {
//            Provider p = JSON.parseObject(JSON.toJSONString(obj), Provider.class); // json 获取 ，都可以实现
            Provider p = new ObjectMapper().convertValue(obj, Provider.class);  // ObjectMapper 获取 ，都可以实现
            return p;
//            return (Provider) obj;  (强转失败)
        }
        // 2.如果缓存中没有,则查数据库,然后添加到缓存中
//        Provider provider = providerMapper.getProviderByPid(pid);
        Provider provider = new Provider();
        provider.setPid(3);
        provider.setProviderCode("北京");
        provider.setFax("ssss1");
        redisClient.set(pid, provider);
        return provider;
    }


}
